package com.ruoyi.web.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.web.dto.ChargingRecordsDto;
import com.ruoyi.web.entity.Charges;
import com.ruoyi.web.entity.ChargingRecords;
import com.ruoyi.web.entity.Pile;
import com.ruoyi.web.entity.Station;
import com.ruoyi.web.service.IChargesService;
import com.ruoyi.web.service.IChargingRecordsService;
import com.ruoyi.web.service.IPileService;
import com.ruoyi.web.service.IStationService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lqc
 * @since 2024-02-01
 */
@RestController
@RequestMapping("/admin/chargingRecords")
public class ChargingRecordsController extends BaseController {

    private final IChargingRecordsService chargingRecordsService;
    private final IPileService pileService;
    private final IStationService stationService;
    private final IChargesService chargesService;


    public ChargingRecordsController(IChargingRecordsService chargingRecordsServiceImpl, IPileService pileService, IStationService stationService, IChargesService chargesService) {
        this.chargingRecordsService = chargingRecordsServiceImpl;
        this.pileService = pileService;
        this.stationService = stationService;
        this.chargesService = chargesService;
    }

    /**
     * 查询充电记录列表
     */
    @PreAuthorize("@ss.hasPermi('admin:chargingRecords:list')")
    @GetMapping("/list")
    public TableDataInfo list(ChargingRecords chargingRecords) {
        startPage();
        List<ChargingRecordsDto> list = chargingRecordsService.selectChargingRecordsList(chargingRecords);
        return getDataTable(list);
    }

    /**
     * 导出充电记录列表
     */
    @PreAuthorize("@ss.hasPermi('admin:chargingRecords:export')")
    @Log(title = "充电记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ChargingRecords chargingRecords) {
        List<ChargingRecordsDto> list = chargingRecordsService.selectChargingRecordsList(chargingRecords);
        ExcelUtil<ChargingRecordsDto> util = new ExcelUtil<ChargingRecordsDto>(ChargingRecordsDto.class);
        util.exportExcel(response, list, "充电记录数据");
    }

    /**
     * 获取充电记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('admin:chargingRecords:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(chargingRecordsService.selectChargingRecordsById(id));
    }

    /**
     * 新增充电记录
     */
    @PostMapping("/add/{pileId}")
    public AjaxResult add(@PathVariable Long pileId) {
        Pile pile = pileService.getById(pileId);
        if (pile == null) {
            return AjaxResult.error("未找到对应的充电桩ID：" + pileId);
        }
        Station station = stationService.getById(pile.getStationId());
        if (station == null) {
            return AjaxResult.error("未找到对应的充电站ID：" + pile.getStationId());
        }

        ChargingRecords chargingRecords = new ChargingRecords();
        chargingRecords.setId(IdUtil.getSnowflakeNextId());
        chargingRecords.setPileId(pileId); // 确保设置了pileId
        chargingRecords.setChargeOrderNumber(generateChargeOrderNumber());
        LoginUser loginUser = getLoginUser();
        if (loginUser == null || loginUser.getUserId() == null) {
            return AjaxResult.error("无法获取当前登录用户信息");
        }
        Long userId = loginUser.getUserId();
        chargingRecords.setCustomerId(userId);
//        chargingRecords.setConsumptionAmount(RandomUtil.randomLong(0,100000));
//        chargingRecords.setChargedElectricity(RandomUtil.randomLong(0,20000));
        chargingRecords.setStationName(station.getStationName());
        chargingRecords.setStatus("1");

        return toAjax(chargingRecordsService.insertChargingRecords(chargingRecords));
    }

    private String generateChargeOrderNumber() {
        // 使用日期时间，精确到毫秒
        String dateTime = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        // 生成一个四位数的随机数
        int randomNumber = ThreadLocalRandom.current().nextInt(1000, 10000);
        // 返回组合后的充电单号
        return "CD_" + dateTime + randomNumber;
    }

    @GetMapping("/endCharging/{id}")
    public AjaxResult endCharging(@PathVariable Long id) {
        ChargingRecords chargingRecords = chargingRecordsService.getById(id);
        Long chargesId = pileService.getById(chargingRecords.getPileId()).getChargesId();
        Charges charges = chargesService.getById(chargesId);
        Long l = RandomUtil.randomLong(10, 20000);
        Long amount = 0L;
        if (charges.getTypeName().equals("按量收费")) {
            amount = l * 150;
        }
        chargingRecordsService.update(Wrappers.lambdaUpdate(ChargingRecords.class)
                .eq(ChargingRecords::getId, id)
                .set(ChargingRecords::getConsumptionAmount, amount)
                .set(ChargingRecords::getChargedElectricity, l));
        return success();
    }

    /**
     * 修改充电记录
     */
    @PreAuthorize("@ss.hasPermi('admin:chargingRecords:edit')")
    @Log(title = "充电记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ChargingRecords chargingRecords) {
        return toAjax(chargingRecordsService.updateChargingRecords(chargingRecords));
    }

    /**
     * 删除充电记录
     */
    @PreAuthorize("@ss.hasPermi('admin:chargingRecords:remove')")
    @Log(title = "充电记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(chargingRecordsService.deleteChargingRecordsByIds(ids));
    }
}
